<script lang="ts" setup>
import type { RenderContent } from '@arco-design/web-vue/es/_utils/types'
import type { DnsRecordItem, DnsResolveDomainListItem } from '@/apis/model/dns'
import { Message } from '@arco-design/web-vue'
import {
  deleteDnsAuthorityRecordApi,
  getDnsAuthorityDomainApi,
  getDnsAuthorityDomainCheckNameserverStatusApi,
  getDnsAuthorityRecordsListApi,
} from '@/apis/modules/dns'
import { commonTableProps } from '@/utils/table'
import EditDialog from '../components/EditorDialog.vue'
import EditRecordDialog from './components/EditRecordDialog.vue'
import EditRemarkDialog from './components/EditRemarkDialog.vue'
import useConfig from './useConfig'

const route = useRoute()
const router = useRouter()
const {
  visible: editorRemarkDialogVisible,
  open: openEditorRemarkDialog,
  data: editorRemarkDialogData,
} = usePopup()
const {
  visible: editRecordDialogVisible,
  open: openEditRecordDialog,
  data: editRecordDialogData,
} = usePopup()
const {
  visible: editDialogVisible,
  open: openEditDialog,
  data: editDialogData,
} = usePopup()
const { tableColumns } = useConfig()
const queryParams = ref({ name_keyword: '', domain: route.params.name })
const refreshLoading = ref(false)
const loading = ref(false)
const basicInfo = ref<DnsResolveDomainListItem>({})
const {
  loading: tableLoading,
  data: tableData,
  run,
} = useListRequest(getDnsAuthorityRecordsListApi, {
  params: queryParams,
  immediate: true,
})
// 删除记录
function handleDelete(record: DnsRecordItem) {
  ModalHelper.error({
    title: '删除记录',
    content: h('div', null, [
      '确定要删除 “',
      h('span', { class: 'text-[#FA5566]' }, `${record.name || '-'}`),
      '” 记录吗？',
    ]) as unknown as RenderContent,
    okText: '删除',
    width: 480,
    closable: false,
    onOk: async () => {
      await deleteDnsAuthorityRecordApi({ id: record.id })
      await run()
      Message.success('删除成功')
    },
  })
}
async function handleRefresh() {
  if (refreshLoading.value)
    return Message.warning('正在刷新中...')
  refreshLoading.value = true
  await getDnsAuthorityDomainCheckNameserverStatusApi({
    id: basicInfo.value?.id,
  })
    .then((res: any) => {
      basicInfo.value!.nameserver_status = res.status
    })
    .finally(() => (refreshLoading.value = false))
}
function shouldShowTooltip(remark: string) {
  if (!remark)
    return false
  return remark.length > 50 // 先按字符数快速判断
}
async function getAnalysisDetail() {
  const id = route.params.id as string
  const name = route.params.name as string
  loading.value = true
  await getDnsAuthorityDomainApi({ id, name })
    .then((res: DnsResolveDomainListItem) => {
      basicInfo.value = res
    })
    .finally(() => (loading.value = false))
}
onMounted(() => {
  getAnalysisDetail()
})
</script>

<template>
  <main-container
    :loading="tableLoading || loading"
    :show-pagination="false"
    :breadcrumb="route.params.name"
    @run="run"
  >
    <div class="detail-container">
      <div class="detail-title">
        <span>基础信息</span>
        <a-button
          class="ml-auto shrink-0 !border-none !bg-white"
          type="outline"
          :disabled="loading"
          @click="openEditDialog(basicInfo)"
        >
          <template #icon>
            <i-icons-edit :class="{ 'animate-spin': loading }" />
          </template>
        </a-button>
      </div>
      <div class="detail-domain-box">
        <div class="detail-domain-item">
          <div class="detail-item-title">
            域名
          </div>
          <div class="detail-item-value">
            {{ basicInfo?.name || '-' }}
          </div>
        </div>
        <div class="detail-domain-item !flex">
          <div class="detail-item-title">
            接入状态
          </div>
          <section class="flex items-center gap-x-1">
            <section v-if="!refreshLoading">
              <div
                v-if="basicInfo?.nameserver_status === 1"
                class="flex items-center gap-x-1 !text-xs"
                style="line-height: normal !important"
              >
                <i-icons-failed />
                未接入
              </div>
              <div
                v-else
                class="flex items-center gap-x-1 !text-xs"
                style="line-height: normal !important"
              >
                <i-icons-success />
                已接入
              </div>
            </section>
            <span
              v-else
              style="line-height: normal !important"
            >检测中</span>
            <i-icons-refresh
              class="table-icon cursor-pointer text-[#00A65B]"
              :class="{ 'animate-spin': refreshLoading }"
              @click="handleRefresh()"
            />
          </section>
        </div>
        <div class="detail-domain-item">
          <div class="detail-item-title">
            备注
          </div>
          <div class="detail-item-value">
            {{ basicInfo?.remark || '-' }}
          </div>
        </div>
        <div class="detail-domain-item">
          <div class="detail-item-title">
            服务器地址
          </div>
          <div class="detail-item-value">
            <div class="flex items-center whitespace-nowrap">
              <section
                v-for="(ns, i) in basicInfo?.expected_nameservers"
                :key="ns.id"
              >
                {{ ns.nameserver_hostname }}
                <a-divider
                  v-if="i !== basicInfo?.expected_nameservers!.length - 1"
                  direction="vertical"
                />
              </section>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="my-6 flex items-center">
      <div class="flex space-x-4">
        <a-button
          type="primary"
          @click="openEditRecordDialog"
        >
          新建记录
        </a-button>
        <a-input-search
          v-model="queryParams.name_keyword"
          placeholder="请输入主机记录搜索"
          class="!w-58"
          allow-clear
          @clear="run()"
          @search="run()"
          @keydown.enter="run()"
        />
      </div>
      <a-button
        class="ml-auto shrink-0 text-color-1"
        type="outline"
        :disabled="tableLoading"
        @click="run"
      >
        <template #icon>
          <i-icons-refresh :class="{ 'animate-spin': tableLoading }" />
        </template>
      </a-button>
    </div>
    <a-table
      v-bind="commonTableProps"
      :columns="tableColumns"
      :data="tableData"
    >
      <template #ttl="{ record }">
        {{ getOptionsLabel(ttlOptions, record.ttl) }}
      </template>
      <template #remark="{ record }">
        <div class="flex">
          <a-tooltip
            :content="record.remark || '-'"
            position="top"
            :disabled="!shouldShowTooltip(record.remark)"
          >
            <span class="overflow-hidden text-ellipsis whitespace-nowrap">
              {{ record.remark || '-' }}
            </span>
          </a-tooltip>
          <div
            v-if="record.gtm_instance_id === '0'"
            class="ml-1 min-w-4"
          >
            <i-icons-edit
              class="table-icon"
              size="16px"
              @click="openEditorRemarkDialog(record)"
            />
          </div>
        </div>
      </template>
      <template #actions="{ record }">
        <section
          v-if="record.gtm_instance_id === '0'"
          class="flex items-center gap-x-1"
        >
          <a-link
            :hoverable="false"
            @click="openEditRecordDialog(record)"
          >
            <i-icons-edit size="16px" />
          </a-link>
          <a-link
            :hoverable="false"
            status="danger"
            @click="handleDelete(record)"
          >
            <i-icons-delete size="16px" />
          </a-link>
        </section>
        <a-tooltip
          v-else
          content="前往 GTM 实例"
          position="top"
        >
          <a-link
            class="!hover:bg-[#E5E6EB]"
            @click="router.push({ name: 'DnsInstanceList' })"
          >
            <i-icons-instance />
          </a-link>
        </a-tooltip>
      </template>
    </a-table>
    <edit-dialog
      v-model:visible="editDialogVisible"
      :record="editDialogData"
      @reload="getAnalysisDetail"
    />
    <edit-remark-dialog
      v-model:visible="editorRemarkDialogVisible"
      :record="editorRemarkDialogData"
      @reload="run"
    />
    <edit-record-dialog
      v-model:visible="editRecordDialogVisible"
      :record="editRecordDialogData"
      @reload="run"
    />
  </main-container>
</template>

<style lang="less" scoped>
.detail-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;
  align-self: stretch;
  border-radius: var(--border-radius-lg, 8px);
  border: 1px solid var(--border-1, #f2f3f5);
  background: #fff;
  .detail-title {
    width: 100%;
    height: 56px;
    line-height: 56px;
    padding: 0 16px;
    background-color: #f7f8fa;
    font-size: 14px;
    font-weight: bold;
    display: flex;
    align-items: center;
  }

  .detail-domain-box {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    align-items: center;
    padding: 24px 16px;
    gap: 24px 16px;
    align-self: stretch;

    .detail-domain-item {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      gap: 8px;
      flex: 1 0 0;
      .detail-item-title {
        color: var(--text-3, #86909c);
        font-family: 'Microsoft YaHei UI';
        font-size: 12px;
        font-style: normal;
        font-weight: 400;
        line-height: normal;
      }

      .detail-item-value {
        color: #1d2129;
        line-height: 16px;
        display: flex;
        align-items: center;
        column-gap: 4px;
        font-family: 'Microsoft YaHei UI';
        font-size: 12px;
        font-style: normal;
        font-weight: 400;
        line-height: normal;
        @apply !whitespace-pre-line break-all;
      }
    }
  }
}
:deep(.arco-table-tr) {
  .table-icon {
    opacity: 0;
    color: var(--color-text-7);
    cursor: pointer;
  }

  &:hover {
    .table-copy-text {
      @apply text-primary;
    }

    .table-icon {
      opacity: 1;
      color: #00a65b;
    }
  }
}
</style>
